#!/usr/bin/with-contenv bashio
# vim: ft=bash
# shellcheck shell=bash
# ==============================================================================
# Start universal-silabs-flasher if requested
# ==============================================================================

# shellcheck disable=SC2034
declare autoflash_firmware
declare device
declare firmware
declare usb_device_path
declare usb_manufacturer
declare usb_product
declare gpio_reset_flag

function exit_no_firmware {
    bashio::log.warning "No firmware found for the selected device, assuming firmware is installed."
    exit 0
}

# Function to check if the device is Home Assistant Yellow
function is_home_assistant_yellow {
    # First, ensure the device is /dev/ttyAMA1
    if [ "${device}" != "/dev/ttyAMA1" ]; then
        return 1
    fi

    # Check the known paths for Home Assistant Yellow
    local paths=(
        "/sys/devices/platform/soc/fe201800.serial/tty/ttyAMA1"
        "/sys/devices/platform/axi/1000120000.pcie/1f0003c000.serial/tty/ttyAMA1"
    )
    for path in "${paths[@]}"; do
        if [ -d "${path}" ]; then
            return 0
        fi
    done
    return 1
}

device=$(bashio::config 'device')
gpio_reset_flag=""

if bashio::config.false 'autoflash_firmware'; then
    bashio::log.info "Flashing firmware is disabled"
    exit 0
fi

if bashio::config.has_value 'network_device'; then
    bashio::log.info "Network device is selected, skipping firmware flashing"
    exit 0
fi

if is_home_assistant_yellow; then
    bashio::log.info "Detected Home Assistant Yellow"
    firmware="yellow_openthread_rcp_2.4.4.0_GitHub-7074a43e4_gsdk_4.4.4.gbl"
    gpio_reset_flag="--bootloader-reset yellow"
else
    # Check device manufacturer/product information
    # shellcheck disable=SC2046,SC2086
    usb_device_path=$(realpath /sys/class/tty/$(readlink /sys/class/tty/$(basename ${device}) | sed 's:/[^/]*tty[^/]*::g' )/../)
    if [ ! -f "${usb_device_path}/idProduct" ]; then
        bashio::log.info "The selected serial port is not a USB device."
        exit_no_firmware
    fi

    if [ ! -f "${usb_device_path}/manufacturer" ] || [ ! -f "${usb_device_path}/product" ]; then
        bashio::log.info "USB device is missing manufacturer or product name."
        exit_no_firmware
    fi

    usb_manufacturer=$(cat "${usb_device_path}/manufacturer")
    usb_product=$(cat "${usb_device_path}/product")

    bashio::log.info "Checking ${device} identifying ${usb_product} from ${usb_manufacturer}."
    if [[ "${usb_manufacturer}" == "Nabu Casa" && "${usb_product}" == "SkyConnect"* ]]; then
        firmware="skyconnect_openthread_rcp_2.4.4.0_GitHub-7074a43e4_gsdk_4.4.4.gbl"
    elif [[ "${usb_manufacturer}" == "Nabu Casa" && "${usb_product}" == "Home Assistant Connect ZBT-1"* ]]; then
        firmware="skyconnect_openthread_rcp_2.4.4.0_GitHub-7074a43e4_gsdk_4.4.4.gbl"
    elif [[ "${usb_manufacturer}" == "ITEAD" && "${usb_product}" == "SONOFF Zigbee 3.0 USB Dongle Plus V2" ]]; then
        firmware="ot-rcp-v2.4.2.0-zbdonglee-460800.gbl"
        gpio_reset_flag="--bootloader-reset sonoff"
    elif [[ "${usb_manufacturer}" == "SMLIGHT" && "${usb_product}" == "SMLIGHT SLZB-07" ]]; then
        firmware="ot-rcp-v2.4.2.0-slzb-07-460800.gbl"
        gpio_reset_flag="--bootloader-reset slzb07"
    else
        exit_no_firmware
    fi
fi

bashio::log.info "Starting universal-silabs-flasher with ${device}"
# shellcheck disable=SC2086
exec universal-silabs-flasher --device ${device}  ${gpio_reset_flag}  \
     flash --ensure-exact-version --allow-cross-flashing --firmware "/root/${firmware}"
